package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.hebeimodule.socket.mod.MSG_Comment;
import com.mediacloud.app.assembly.common.MD5Encoder;
import com.mediacloud.app.cloud.ijkplayersdk.auth.AesCBC;
import com.mediacloud.app.quanzi.model.BaseDataListBean;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.JSONObjectConvertFactory;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediacloud.app.user.net.SignInterceptor;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import beecloudpaysdk.utils.net.PayDataInvokeUtils;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.QueryMap;

/**
 * 评论域名
 */
public class CommentApi {

    private static ICommentApi commentApi;
    private static ICommentApi commentJson;

    public static ICommentApi getCommentApi(Context context){
        if(commentApi == null){
            synchronized (CommentApi.class){
                if(commentApi == null) {
                    initCommentApi(context.getApplicationContext());
                }
            }
        }
        return commentApi;
    }

    private static void initCommentApi(Context context){
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).comment_client;
        if(TextUtils.isEmpty(baseUrl)){
            Log.e("DataInvokeUtil","initSpiderCmsApi failed spider_cms is null");
            return;
        }
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dns(new MyDns());
        ProxyUtil.config(builder);
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).comment_client, AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_comment_client));
        builder.addInterceptor(interceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl+"/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        commentApi = retrofit.create(ICommentApi.class);
        String key = context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid);
        String iv = context.getResources().getString(com.mediacloud.app.reslib.R.string.httprequest_encrypt_key);
        String skey = MD5Encoder.encode(key).toLowerCase().substring(8, 24);
        String siv = MD5Encoder.encode(iv).toLowerCase().substring(8, 24);
        PayDataInvokeUtils.accessKeyId = AesCBC.getInstance().decrypt(
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.access_key_id , "utf-8", skey, siv, true
        );
        PayDataInvokeUtils.accessKeySecret = AesCBC.getInstance().decrypt(
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.access_key_secret,
                "utf-8", skey, siv, true);
        String sendParams = PayDataInvokeUtils.kongSign(PayDataInvokeUtils.getPublicParamsMap());
    }

    public static ICommentApi getCommentApiJson(Context context) {
        if (commentJson == null) {
            synchronized (CommentApi.class) {
                if (commentJson == null) {
                    initCommentApiJson(context.getApplicationContext());
                }
            }
        }
        return commentJson;
    }

    private static void initCommentApiJson(Context context) {
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).comment_client;
        if (TextUtils.isEmpty(baseUrl)) {
            Log.e("DataInvokeUtil", "initSpiderCmsApi failed spider_cms is null");
            return;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).comment_client, AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_comment_client));
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        ProxyUtil.config(builder);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(new JSONObjectConvertFactory())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        commentJson = retrofit.create(ICommentApi.class);
    }

    public interface ICommentApi {

        @GET("api/comment/findMicroCommentList")
        Call<BaseDataListBean<MSG_Comment>> getCommentList(@QueryMap Map<String,Object> body, @Header("tenantId") String tenantId);
    }
}